package com.itbuka.oauth.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;

import com.itbuka.oauth.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Map login(String username, String password, String clientId, String clientSecret, Integer ttl) {
        //参数
        Map parm = new HashMap<>();
        parm.put("username", username);
        parm.put("password", password);
        parm.put("client_id", clientId);
        parm.put("client_secret", clientSecret);
        parm.put("grant_type", "password");
        //通过hutool工具远程调用
        String post = HttpUtil.post("http://localhost:9200/oauth/token", parm);
        //返回值转成map类型数据
        Map<String, String> map = JSONObject.parseObject(post, Map.class);
        //保存到redis中
        redisTemplate.opsForValue().set(map.get("jti"), map.get("access_token"), ttl, TimeUnit.HOURS);
        return map;
    }
}
